package com.atguigu.spzx.cart.service.Impl;

import com.atguigu.spyx.model.common.Result;
import com.atguigu.spyx.model.common.ResultCodeEnum;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.h5.CartItem;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.h5.UserInfo;
import com.atguigu.spyx.model.common.com.atguigu.spyx.model.entity.product.ProductSku;
import com.atguigu.spyx.model.exception.SpzxException;
import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.common.interceptor.SpzxUserInterceptor;
import com.atguigu.spzx.product.api.ProductClient;


import jakarta.annotation.Resource;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LT
 * @create 2023-11-20-21:14
 */
@Service
public class CartServiceImpl implements CartService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ProductClient productClient;
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        UserInfo userInfo = SpzxUserInterceptor.THREAD_LOCAL.get();
        Long userId = userInfo.getId();
        BoundHashOperations<String,String, CartItem> ops = redisTemplate.boundHashOps("user:cart:"+userId);
        CartItem cartItem = ops.get(skuId.toString());
        if (cartItem==null){
            cartItem = new CartItem();
            cartItem.setUserId(userId);
            cartItem.setSkuId(skuId);
            cartItem.setSkuNum(skuNum);
            cartItem.setCreateTime(new Date());
            Result<ProductSku> result = productClient.findById(skuId);
            if (result.getCode()!=200){
                throw new SpzxException(ResultCodeEnum.ERROR , null);
            }
            ProductSku productSku = result.getData();
            cartItem.setCartPrice(productSku.getSalePrice());
            cartItem.setImgUrl(productSku.getThumbImg());
            cartItem.setSkuName(productSku.getSkuName());
        } else {
            cartItem.setSkuNum(cartItem.getSkuNum()+skuNum);
        }
        cartItem.setUpdateTime(new Date());
        cartItem.setIsChecked(1);
        ops.put(skuId.toString() , cartItem);

    }

    @Override
    public List<CartItem> cartList() {
        BoundHashOperations<String,String, CartItem> ops = getCart();
        return  ops.values();
    }

    @Override
    public void deleteCartItem(Long skuId) {
        BoundHashOperations<String,String, CartItem> cart = getCart();
        cart.delete(skuId.toString());
    }

    @Override
    public void clearCart() {
        Long userId = SpzxUserInterceptor.THREAD_LOCAL.get().getId();
        redisTemplate.delete("user:cart:"+userId);
    }

    @Override
    public void checkCart(Long skuId, Integer status) {
        BoundHashOperations<String,String, CartItem> cart = getCart();
        CartItem cartItem = cart.get(skuId.toString());
        if (cartItem!=null){
            cartItem.setIsChecked(status);
            cart.put(skuId.toString(),cartItem);
        }
    }

    @Override
    public void allCheckCart(Integer status) {
        BoundHashOperations<String,String, CartItem> cart = getCart();
        cart.entries().forEach((skuIdStr , cartItem)->{
            cartItem.setIsChecked(status);
            cart.put(skuIdStr,cartItem);
        });
    }

    @Override
    public List<CartItem> checkedCartList() {
        return getCart().values().stream().filter(cartItem ->
                cartItem.getIsChecked().intValue()==1)
                .collect(Collectors.toList());
    }

    @Override
    public void deleteCheckedCart() {
        BoundHashOperations<String,String, CartItem> cart = getCart();
        cart.entries().forEach((skuIdStr , cartItem)->{
            if (cartItem.getIsChecked().intValue()==1){
                cart.delete(skuIdStr);
            }
        });
    }

    private BoundHashOperations<String, String, CartItem> getCart() {
        //1、获取当前用户的购物车(就是当前用户存储购物项的hash结构)
        Long userId = SpzxUserInterceptor.THREAD_LOCAL.get().getId();
        //  user:cart:userId    skuId     cartItem
        BoundHashOperations<String,String, CartItem> ops =
                redisTemplate.boundHashOps("user:cart:" + userId);
        return ops;
    }
}
